<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2015/9/23
 * Time: 15:53
 */
class Sms
{
    const POSTURL = 'http://139.129.128.71:8086/msgHttp/json/mt';

    const NOT_SUFFICIENT_FUNDS = -1;//余额不足导致发送失败

    const USER_ERR = -2;//短信网关帐号错误

    const PWD_ERR   =-3;//密码错误

    const ARG_ERR  = -4;//参数不对应

    const IS_NOT_PHONE = -5;//手机号码不正确

    const CAN_NOT_REPEAT_SEND  = -6;//不允许重复发送

    const NO = -7 ;//未知原因

    const UPDATE_ERR = -8;//更新状态失败

    const WRITE_ERR = -9;//写入数据库失败

    const HAVE_NO_ROWS  = -10;//没有要发送的数据

    const OK = 1;//成功

    const WAIT = 2;//等待发送

    const REPEATIME = 60;     //重复发送的间隔，秒。
    const FAILTIME = 1800;      //失效的时间，秒。
    const CHANNELID = 1;
    const NOWTIME = 0;

    private static $config =array(
        'account'=>array(
            1 => array(
                'username'    =>'sumao106',  //独立通道,用作系统自动发送
                'password'   => '123456',
                'url'      =>'http://139.129.128.71:8086/msgHttp/json/mt'
            ),
            2 => array(
                'username'    =>'sumaoyx',  //营销通道，用作人为发送
                'password'   => '123456',
                'ID'   =>    '707',
                'url'  =>    'www.591duanxin.com/sms.aspx'
            )
        ),
        'suffix'      =>'[退订回复T]【塑料交易网】'
    );

    public static  function  send($mobile,$cdata,$channel,$dataType){
        if ($channel == 1){
            if($dataType == 'Login' || $dataType=='Findpassword' || $dataType=='Register'){
                $senddata = array(
                    'channel_id'=> self::CHANNELID,
                    'receiver' =>  $cdata['mobile'],
                    'type'  =>$dataType,
                    'content'=>  $cdata['content'],
                    'code'   => $cdata['code'],
                    'status' => self::OK,
                    'worker_id'=> "1",
                    'send_time'=> time()
                );
                $db = new BaseModel();
                $sms_id =  $db->getDB()->fetchOne("select id from sendsms where  receiver ='{$mobile}'AND type = '{$dataType}'");
                if($sms_id){
                    $sms_idt = $db->getDB()->update('sendsms',$senddata," id = {$sms_id}");
                    if(empty($sms_idt)){
                        echo self::UPDATE_ERR;
                    }
                }else{
                    $sms_idt = $db->getDB()->insert('sendsms',$senddata);
                    if(empty($sms_idt)){
                        return self::WRITE_ERR;
                    }
                }
            }

            //这个二货 一次最多20条  就是要对号码 2条一个分组
            $mb =  explode(";",$mobile);
            //次数
            $rs = "";
            $arr = array_chunk($mb,20);
            foreach ($arr as $key =>$value ){
                $mobile = implode(",",$value);
                $timestamps = time()*1000;
                $mobile =      preg_replace("/;/i",",",$mobile);
                $data = array(
                    "account" => self::$config['account'][$channel]['username'],
                    "password" => md5(self::$config['account'][$channel]['password'].$mobile.$timestamps),
                    "content" => urlencode($cdata['content'].self::$config['suffix']),
                    "mobile" => $mobile,
                    "timestamps" => $timestamps,
                );
                $rs = self::https_request(self::POSTURL,$data);
            }
            //开始发送
            return $rs;
        }else if ($channel == 2){
            $mobile =  preg_replace("/;/i",",",$mobile);
            $data = array(
                'userid'=>self::$config['account'][$channel]['ID'],
                "account" => self::$config['account'][$channel]['username'],
                "password" => self::$config['account'][$channel]['password'],
                "content" => $cdata['content'].self::$config['suffix'],
                "mobile" => $mobile,
                "sendTime" => "",
                'action'=>'send',
                'extno'=>'',
            );
            $rs = self::https_request2(self::$config['account'][$channel]['url'],$data);
            //开始发送
            return $rs;
        }
    }



    public static function DatabaseSend($mobile,$cdata, $channel,$dataType ='Login'){
        if($dataType == 'Login' || $dataType=='Findpassword' || $dataType=='Register'){
            $senddata = array(
                'channel_id'=> self::CHANNELID,
                'receiver' =>  $cdata['mobile'],
                'type'  =>$dataType,
                'content'=>  $cdata['content'],
                'code'   => $cdata['code'],
                'status' => self::OK,
                'worker_id'=> "1",
                'send_time'=> time()
            );
            $db = new BaseModel();
            $sms_id =  $db->getDB()->fetchOne("select id from sendsms where  receiver ='{$mobile}'AND type = '{$dataType}'");
            if($sms_id){
                $sms_idt = $db->getDB()->update('sendsms',$senddata," id = {$sms_id}");
                if(empty($sms_idt)){
                    echo self::UPDATE_ERR;
                }
            }else{
                $sms_idt = $db->getDB()->insert('sendsms',$senddata);
                if(empty($sms_idt)){
                    return self::WRITE_ERR;
                }
            }
        }
        $timestamps = time()*1000;
        $data = array(
            "account" => self::$config['account'][$channel]['username'],
            "password" => md5(self::$config['account'][$channel]['password'].$mobile.$timestamps),
            "content" => urlencode($cdata['content'].self::$config['suffix']),
            "mobile" => $mobile,
            "timestamps" => $timestamps,
        );
        return self::https_request(self::POSTURL,$data);
    }


    /**
     *这是查询余额
     * @param $channel
     * @return mixed
     */
    public static  function checkBlance($channel){

        $timestamps = time()*1000;
        $data = array(
            "account" => self::$config['account'][$channel]['username'],
            "password" => md5(self::$config['account'][$channel]['password'].$timestamps),
            "timestamps" => $timestamps,
        );
        return self::https_request("http://139.129.128.71:8086/msgHttp/json/balance",$data);
    }

    /**
     * 发送短信
     * @param $url
     * @param null $data
     * @return mixed
     */
    private static function https_request($url,$data =NULL){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_HEADER, false);
        curl_setopt($curl,CURLOPT_POST, true);
        curl_setopt($curl,CURLOPT_BINARYTRANSFER,false);
        $post_data = http_build_query($data);
        curl_setopt($curl, CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $rs =  json_decode($output,1);
        if (!empty($rs['Rets'][0]['Msg_Id'])){
            return $rs['Rets'][0]['Msg_Id'];
        }
        return $output;
    }

    private static function https_request2($url,$data =NULL){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_HEADER, false);
        curl_setopt($curl,CURLOPT_POST, true);
        curl_setopt($curl,CURLOPT_BINARYTRANSFER,false);
        $post_data = http_build_query($data);

        curl_setopt($curl, CURLOPT_POSTFIELDS,$post_data);
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        $rs =  simplexml_load_string($output);

        if ($rs->taskID){

            return $rs->taskID;
        }


    }

}